const { Controller } = require("egg");
const path = require("path");
const fs = require("fs");
const { respAdapter } = require("../../utils");
const xlsx = require("node-xlsx");
class ManagerFrameController extends Controller {
  async list() {
    const { ctx, app, config } = this;
    try {
      const query = ctx.query;
      let params = [];

      let sqlQuery = "SELECT * FROM manager";
      console.log("😈query", query);

      for (const [key, value] of Object.entries(query)) {
        if (value) {
          if (sqlQuery.indexOf("WHERE") == -1) {
            sqlQuery += " WHERE";
            params.push(`%${value}%`);
          }
          // 确保只有当搜索字符串不为空时才添加条件
          sqlQuery += ` ${key} LIKE ? `;
        }
      }

      sqlQuery = sqlQuery.replace(/ AND $/, "");
      sqlQuery += "  ORDER BY created_time DESC";
      console.log("sqlQuery", sqlQuery);

      const list = await this.app.mysql.query(sqlQuery, params);

      if (!list) {
        ctx.body = respAdapter(null, "数据异常，请重试", false);
      }

      ctx.body = respAdapter({ list });
    } catch (err) {
      console.log("😈err", err);
      ctx.body = respAdapter(null, err, false);
    }
  }

  async detail() {
    const { ctx, app, config } = this;
    try {
      const query = ctx.query;
      const data = await this.app.mysql.get("manager", query);

      if (!data) {
        ctx.body = respAdapter(null, "数据异常，请重试", false);
      }

      ctx.body = respAdapter({
        ...data,
      });
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }

  async eventList() {
    const { ctx, app, config } = this;
    try {
      const query = ctx.query;
      console.log("😈query", query);
      const list = await this.app.mysql.select("event", {
        where: query,
        orders: [
          ["created_time", "DESC"], // 指定时间字段和降序排序
        ],
      });

      if (!list) {
        ctx.body = respAdapter(null, "数据异常，请重试", false);
      }

      ctx.body = respAdapter({ list });
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }
}

module.exports = ManagerFrameController;
